package com.yifeng.repo.base.api;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by daibing on 2023/8/6.
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TimeRange {
    private LocalTime start;
    private LocalTime end;

    /**
     * 09:00~11:30,14:00~17:30,19:00~20:30
     */
    public static List<TimeRange> parse(String timeRangesText) {
        return parse(timeRangesText, "~", false);
    }

    public static List<TimeRange> parse(String timeRangesText, String seperator, boolean addZeroPrefix) {
        if (timeRangesText == null || timeRangesText.trim().length() == 0) {
            return Collections.emptyList();
        }
        String[] timeRangeTextList = timeRangesText.split(",");
        List<TimeRange> timeRangeList = new ArrayList<>(timeRangeTextList.length);
        for (String s : timeRangeTextList) {
            String[] timeTextList = s.split(seperator);
            String startText = addZeroPrefix ? zeroFill(timeTextList[0]) : timeTextList[0];
            String endText = addZeroPrefix ? zeroFill(timeTextList[1]) : timeTextList[1];
            timeRangeList.add(new TimeRange(LocalTime.parse(startText), LocalTime.parse(endText)));
        }
        return timeRangeList;
    }

    public static TimeRange parseOne(String timeRangesText) {
        return parseOne(timeRangesText, "~", false);
    }

    public static TimeRange parseOne(String timeRangesText, String seperator, boolean addZeroPrefix) {
        if (timeRangesText == null || timeRangesText.trim().length() == 0) {
            return null;
        }
        String[] timeTextList = timeRangesText.split(seperator);
        String startText = addZeroPrefix ? zeroFill(timeTextList[0]) : timeTextList[0];
        String endText = addZeroPrefix ? zeroFill(timeTextList[1]) : timeTextList[1];
        return new TimeRange(LocalTime.parse(startText), LocalTime.parse(endText));
    }

    public static boolean nowInside(List<TimeRange> timeRangeList) {
        LocalTime now = LocalTime.now();
        return timeRangeList.stream().anyMatch(t -> now.isAfter(t.getStart()) && now.isBefore(t.getEnd()));
    }

    private static String zeroFill(String text) {
        if (text.length() == 5) {
            return text;
        } else {
            return "0" + text;
        }
    }
}
